package vip.xiaonuo.hontu.task;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import vip.xiaonuo.core.timer.TimerTaskRunner;
import vip.xiaonuo.facedoor.modular.device.entity.DeviceCategory;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.hontu.issued.util.HongTuRequestUrl;
import vip.xiaonuo.modular.clusterresultpersontrack.service.ClusterResultPersonTrackService;
import vip.xiaonuo.modular.clusterresultstrangertrack.param.ClusterResultStrangerTrackParam;
import vip.xiaonuo.modular.clusterresultstrangertrack.service.ClusterResultStrangerTrackService;
import vip.xiaonuo.modular.clustertaskresult.entity.ClusterTaskResult;
import vip.xiaonuo.modular.clustertaskresult.service.ClusterTaskResultService;

import javax.annotation.Resource;
import java.util.List;

/**
 * 定时同步人员轨迹
 * 10分钟执行一次
 */
@Component
@Slf4j
public class PersonTrackQueryTask implements TimerTaskRunner {

    @Resource
    private ClusterTaskResultService taskResultService;

    @Resource
    private ClusterResultPersonTrackService personTrackService;

    @Resource
    private ClusterResultStrangerTrackService strangerTrackService;

    @Resource
    private DeviceBaseService deviceBaseService;

    @Override
    public void action(String jobParams, String taskId) {
        syncTaskResult();
    }

    @Override
    public void executeXxlJob() throws InterruptedException {
        syncTaskResult();
    }

    private void syncTaskResult(){
        List<DeviceBase> devices = deviceBaseService.list(new LambdaQueryWrapper<DeviceBase>()
                .eq(DeviceBase :: getDeviceType, DeviceCategory.SUB_TYPE_AI_HT+"")
                .eq(DeviceBase :: getDeviceState , "1"));

        for(DeviceBase device : devices){
            List<ClusterTaskResult> results = taskResultService.list(new LambdaQueryWrapper<ClusterTaskResult>()
                    .eq(ClusterTaskResult :: getDeviceId , device.getId()));
            log.info("同步聚类结果，数量：{}",results.size());
            long startTime = System.currentTimeMillis();
            for(ClusterTaskResult result : results){
                if(ObjectUtil.equal(result.getDataType(),0)){ // 聚类任务
                    personTrackService.syncPersonTrack(result);
                }else if(ObjectUtil.equal(result.getDataType(),1)){ // 高频陌生人
                    strangerTrackService.syncStrangerTrack(result);
                }
            }
            log.info("同步耗时：{} ms",System.currentTimeMillis() - startTime);
        }


    }
}
